package com.lagou.config;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;

import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;

/**
 * @author bwcx_jzy
 * @since 2021/11/11
 */
public class SpringApplication {


    public SpringApplication run() throws LifecycleException, ServletException {
        //实例化一个Tomcat
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(getPort());
        tomcat.addWebapp(getContextPath(), createTempDir("tomcat").getAbsolutePath());
        tomcat.start();
        //因为  tomcat.start();是非阻塞型的，所以要阻塞一下，不能让服务停止。
        tomcat.getServer().await();
        return this;
    }

    private String getContextPath() {
        return "/";
    }

    public int getPort() {
        return 8080;
    }

    /**
     * Return the absolute temp dir for given web server.
     *
     * @param prefix server name
     * @return the temp dir for given server.
     */
    protected final File createTempDir(String prefix) {
        try {
            File tempDir = File.createTempFile(prefix + ".", "." + getPort());
            tempDir.delete();
            tempDir.mkdir();
            tempDir.deleteOnExit();
            return tempDir;
        } catch (IOException ex) {
            throw new RuntimeException(
                    "Unable to create tempDir. java.io.tmpdir is set to " + System.getProperty("java.io.tmpdir"), ex);
        }
    }
}
